package com.example.client_group5;

import java.util.ArrayList;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import util.DateUtil;
import util.HttpClientFactory;

import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.content.Intent;

public class FavoriteTweet extends AppBaseActivity {
	int itemsPerPage = 6;
	boolean loadingMore = false;
	boolean loadingHead = false;
	private ArrayList<Tweet> tweets;
	public static UserItemAdapter adapter;
	private int max_id = -1;
	private int since_id = -1;
	private PullToRefreshListView listView;

	private View footerView;
	private ImageManager manager;
	private DateUtil dateUtil;
	private String[] infor;
	private TextView title;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_follow);
		listView = (PullToRefreshListView) findViewById(R.id.ListViewId);
		Bundle b = getIntent().getExtras();
		infor = b.getStringArray("user");
		title = (TextView) findViewById(R.id.title);
		title.setText("Favorite Tweets");
		dateUtil = new DateUtil();
		tweets = new ArrayList<Tweet>();
		registerBaseActivityReceiver();
		manager = ImageManager.getInstance(getApplicationContext());
		adapter = new UserItemAdapter(this, R.layout.listitem, tweets);

		// add the footer before adding the adapter, else the footer will nod
		// load!
		footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.listfooter, null, false);

		listView.addFooterView(footerView);
		listView.setAdapter(adapter);
		// Here is where the magic happens
		listView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {

				Log.d("tag", "loading first....");
				Thread thread = new Thread(null, loadFirstListItems);
				thread.start();
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {

			// useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				// what is the bottom item that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;
				Log.d("tag", "lastInScreen: " + lastInScreen
						+ "/ totalItemCount: " + totalItemCount);
				if ((lastInScreen == totalItemCount) && !(loadingMore)) {
					Log.d("tag", "Loading more item...........");
					loadingMore = true;
					Thread thread = new Thread(null, loadMoreListItems);
					thread.start();
				}
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				if (arg2 >= 1) {

					Tweet tweet = adapter.getItem(arg2 - 1);
					Log.d("content", tweet.content + " /arg2: " + arg2);

					// info[0]: tweet_id, info[1]: fullname, info[2]: username,
					// info[3]: content
					// info[4]: time, info[5]: isRetweeted, info[6]: isFavorite
					// info[7]: retweetedUser, info[8]: user_id, info[9]:
					// image_url, info[10]: img_up_url

					Intent i = new Intent(FavoriteTweet.this, TweetDetail.class);
					Bundle b = new Bundle();
					String[] info = { tweet.tweet_id, tweet.fullname,
							tweet.username, tweet.content, tweet.time,
							"" + tweet.isRetweeted, "" + tweet.isFavorite,
							tweet.retweetedUser, tweet.user_id,
							tweet.image_url, tweet.img_up_url, "f", "f",
							"" + (arg2 - 1) };
					b.putStringArray("tweet", info);
					b.putBoolean("fromFavorite", true);
					b.putStringArray("infor", infor);
					i.putExtras(b);
					startActivity(i);
					// finish();
				}
			}

		});

		title.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeAllActivities();
			}
		});

	}

	private Runnable loadFirstListItems = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			loadingHead = true;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			tweets = new ArrayList<Tweet>();
			max_id = -1;
			since_id = Integer.parseInt(adapter.getItem(0).tweet_id);
			tweets = getTweets(itemsPerPage, since_id, max_id);

			Log.d("tag", "size of first tweets: " + tweets.size());
			if (tweets.size() > 0) {
				since_id = Integer.parseInt(tweets.get(0).tweet_id);
				Log.d("tag", "since id: " + since_id);
			}

			// Done! now continue on the UI thread
			runOnUiThread(returnResult);
		}
	};

	// Runnable to load the items
	private Runnable loadMoreListItems = new Runnable() {
		@Override
		public void run() {
			// Set flag so we cant load new items 2 at the same time
			// loadingMore = true;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			tweets = new ArrayList<Tweet>();
			since_id = -1;
			tweets = getTweets(itemsPerPage, since_id, max_id);
			Log.d("tag", "size of tweets: " + tweets.size());
			if (tweets.size() > 0) {
				// since_id = max_id;
				max_id = Integer
						.parseInt(tweets.get(tweets.size() - 1).tweet_id);
				Log.d("tag", "max id: " + max_id);
			}
			// Done! now continue on the UI thread
			runOnUiThread(returnRes);
		}
	};
	// Since we cant update our UI from a thread this Runnable takes care of
	// that!

	private Runnable returnResult = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (tweets != null && tweets.size() > 0) {
				for (int i = 0; i < tweets.size(); i++)
					adapter.insert(tweets.get(i), 0);
			}
			// Log.d("tag","since_id :"+since_id);
			adapter.notifyDataSetChanged();
			listView.onRefreshComplete();
			/*
			 * if(tweets.size() > 0) loadingHead=false; else
			 * listView.removeHeaderView(headerView);
			 */
		}
	};

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			if (tweets != null && tweets.size() > 0) {
				for (int i = 0; i < tweets.size(); i++) {
					adapter.add(tweets.get(i));
				}

			}
			Log.d("tag", "Adapter size: " + adapter.getCount());
			// Update the Application title
			setTitle("Neverending List with "
					+ String.valueOf(adapter.getCount()) + " items");
			// Tell to the adapter that changes have been made, this will cause
			// the list to refresh
			adapter.notifyDataSetChanged();

			// Done loading more.
			if (tweets.size() > 0) {
				loadingMore = false;
			} else {
				listView.removeFooterView(footerView);

			}
		}
	};

	public ArrayList<Tweet> getTweets(int count, int since_id, int max_id) {
		String getUrl = Setting.ipServer
				+ "api/tweet/get-favorite-tweets?user_id=" + infor[0];
		if (max_id == -1 && since_id == -1)
			getUrl += "&count=" + count;
		else if (max_id != -1)
			getUrl += "&max_id=" + max_id + "&count=" + count;
		else if (since_id != -1)
			getUrl += "&count=" + count + "&since_id=" + since_id;
		Log.d("tag", "url:" + getUrl);

		ArrayList<Tweet> tweets = new ArrayList<Tweet>();

		HttpGet get = new HttpGet(getUrl);

		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		String responseBody = null;
		try {
			responseBody = HttpClientFactory.getThreadSafeClient().execute(get,
					responseHandler);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(responseBody);
			Log.d("tag", jsonObject.toString());
			JSONArray jsonArray = jsonObject.getJSONArray("tweets");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject t = jsonArray.getJSONObject(i);
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
				String img_url = t.getString("img_url").toString();
				String content = t.get("content").toString().trim() + "\n"
						+ img_url;
				boolean isRetweeted = t.getBoolean("is_retweeted");
				boolean isFavorite = t.getBoolean("is_favorite");
				String retweetedUser = t.getString("retweeted_user");

				JSONObject author = t.getJSONObject("author");

				String user_id = author.get("user_id").toString();
				String username = author.get("username").toString();

				String fullname = author.get("fullname").toString();
				String profile_url = author.get("avatar").toString();
				// Log.d("isReweet", "isRetweeted: "+isRetweeted);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id,
						mention, content, img_url, profile_url, time,
						isRetweeted, isFavorite, retweetedUser);
				tweets.add(tweet);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return tweets;
	}

	class UserItemAdapter extends ArrayAdapter<Tweet> {
		private ArrayList<Tweet> tweets;

		public UserItemAdapter(Context context, int textViewResourceId,
				ArrayList<Tweet> tweets) {
			super(context, textViewResourceId, tweets);
			this.tweets = tweets;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.listitem, null);
			}
			Tweet tweet = tweets.get(position);
			if (tweet != null) {
				TextView fullname = (TextView) v.findViewById(R.id.fullname);
				TextView username = (TextView) v.findViewById(R.id.username);
				TextView mention = (TextView) v.findViewById(R.id.mention);
				TextView message = (TextView) v.findViewById(R.id.content);
				ImageView image = (ImageView) v.findViewById(R.id.avatar);
				ProgressBar progressBar = (ProgressBar) v
						.findViewById(R.id.progress_bar);
				ImageView icon = (ImageView) v.findViewById(R.id.icon_id);
				TextView time = (TextView) v.findViewById(R.id.time_id);
				if (fullname != null) {
					fullname.setText(tweet.fullname);
				}
				if (username != null) {
					username.setText(tweet.username);
				}
				if (mention != null) {
					mention.setText(tweet.mention);
				}

				if (message != null) {
					message.setText(tweet.content);
				}
				/*
				 * if(link_img != null){ link_img.setText(tweet.img_up_url); }
				 */
				if (time != null) {
					Log.d("time", tweet.time);
					dateUtil.getDiffDate(tweet.time);
					if (dateUtil.getYear() != 0) {

						time.setText(dateUtil.getYear() + "y");
					} else if (dateUtil.getMonth() != 0) {
						time.setText(dateUtil.getYear() + "M");
					} else if (dateUtil.getDay() != 0) {
						time.setText(dateUtil.getDay() + "d");
					} else if (dateUtil.getHour() != 0) {
						time.setText(dateUtil.getHour() + "h");
					} else if (dateUtil.getMinute() != 0) {
						time.setText(dateUtil.getMinute() + "m");
					} else if (dateUtil.getSecond() != 0) {
						time.setText(dateUtil.getSecond() + "s");
					}
					dateUtil.resetTime();
				}
				if (image != null) {
					image.setTag(tweet.image_url);
					manager.displayImage(tweet.image_url, FavoriteTweet.this,
							image, progressBar);
				}
				if (icon != null) {
					Log.d("isRetweeted", "isRetweeted: " + tweet.isRetweeted
							+ " / " + tweet.content);
					if (tweet.isRetweeted && !tweet.isFavorite) {
						icon.setBackgroundResource(R.drawable.retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if (!tweet.isRetweeted && tweet.isFavorite) {
						icon.setBackgroundResource(R.drawable.favorite_icon1);
						icon.setVisibility(View.VISIBLE);
					}
					if (tweet.isRetweeted && tweet.isFavorite) {
						icon.setBackgroundResource(R.drawable.favorite_retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if (!tweet.isRetweeted && !tweet.isFavorite) {
						icon.setVisibility(View.GONE);
					}
				}

			}

			return v;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return false;

	}

	public void onDestroy() {
		super.onDestroy();
		System.gc();
		unRegisterBaseActivityReceiver();
	}

}